package com.icetech.eom.common.utils;

import com.icetech.eom.common.constant.SecurityConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.UUID;

/**
 *
 * web service 登录用户token生成 token验证 以及过期策略
 * @author wangzw
 * @description 该类只针对
 */
@Component
public class RedisTokenUtil implements Serializable {


    @Autowired
    private StringRedisTemplate redisTemplate;



    /**
     * 创建token
     * @param key
     * @return
     */
    public String createToken(String key) {
        String token = UUID.randomUUID().toString().replace("-", "");
        //失效老的token
        String oldToken = redisTemplate.opsForValue().get(SecurityConstant.WS_USER_TOKEN + key);
        if(StringUtils.isNotBlank(oldToken)){
            redisTemplate.delete(SecurityConstant.WS_TOKEN_PRE + oldToken);
        }
        //存储新的token
        redisTemplate.opsForValue().set(SecurityConstant.WS_USER_TOKEN + key, token);
        redisTemplate.opsForValue().set(SecurityConstant.WS_TOKEN_PRE + token, key);
        return token;
    }

    /**
     * 从token中获取用户名
     * @param token
     * @return
     */
    public String getUsername(String token){
        String username = redisTemplate.opsForValue().get(SecurityConstant.WS_TOKEN_PRE + token);
        return username;
    }

    /**
     * 判断是否已过期
     * @param token
     * @return
     */
    public boolean isExpiration(String token){
        String username = redisTemplate.opsForValue().get(SecurityConstant.WS_TOKEN_PRE + token);
        return StringUtils.isEmpty(username);
    }
}
